package oop.ex3.filemanager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import oop.ex3.common.CommunicationSession;
import oop.ex3.common.Protocol;
import oop.ex3.common.SocketCommunicationSession;

public class RemoteFileManager {

	private String _host;
	private int _port;

	public RemoteFileManager(String host, int port) {
		_host = host;
		_port = port;
	}

	public String getHost() {
		return _host;
	}

	public int getPort() {
		return _port;
	}

	public boolean downloadFile(int localPort, String wantedFile, File directoryPath) {
		boolean result = true;
		try {
			CommunicationSession newSession = createCommunicationSession();
			Protocol.startSession(newSession, localPort);
			newSession.sendString(Protocol.MSG_WANT_FILE);
			newSession.sendString(wantedFile);
			newSession.sendString(Protocol.MSG_END);

			String reply = newSession.readString();
			if (reply.equals(Protocol.MSG_FILE_DOWNLOAD_BEGINS)) {
				byte[] fileInByteArray = newSession.readByteArray();
				translateByteArrayToFile(fileInByteArray, directoryPath, wantedFile);
			} else {
				result = false;
			}
			Protocol.endSession(newSession);
		} catch (IOException e) {
			result = false;
		}
		return result;
	}

	private CommunicationSession createCommunicationSession() throws IOException {
		return new SocketCommunicationSession(_host, _port);
		//return new ConsoleCommunicationSession();
	}

	private void translateByteArrayToFile(byte[] fileInByteArray, File directoryPath, String wantedFile) throws IOException {
		File newFile = new File(directoryPath, wantedFile);
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(newFile);
			out.write(fileInByteArray);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
				}
			}
		}
	}
}